package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.BCrypt;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

@Transactional
@Service
public class ApUserLoginServiceImpl implements ApUserLoginService {


    @Autowired
    private ApUserMapper apUserMapper;


    @Override
    public ResponseResult login(LoginDto dto) {
        //1.判断参数
        if(dto==null ){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if(dto.getEquipmentId()==null && StringUtils.isBlank(dto.getPhone()) && StringUtils.isBlank(dto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //2.判断如果用户名和密码同时不为空，就按照正常登录处理
        if(StringUtils.isNotBlank(dto.getPhone()) && StringUtils.isNotBlank(dto.getPassword())){
            //根据手机号查询用户判断是否存在
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
            if(apUser==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户名不对");
            }

            //获取用户在表中的密文密码
            String loginPwd  = dto.getPassword();//登录的明文密码
            String dbPwd = apUser.getPassword();//表中密文密码

            //比对密码，如果成功生成token
            boolean flag = BCrypt.checkpw(loginPwd, dbPwd);
            if(flag){
                String token = AppJwtUtil.getToken(apUser.getId().longValue());
                Map map = new HashMap<>();
                map.put("token", token);
                apUser.setPassword("");
                map.put("user",apUser);
                return ResponseResult.okResult(map);
            } else {
                //否则密码错误
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);

            }

        } else {
            //3.否则，如果参数中设备ID有值，就按照游客模式处理
            if(dto.getEquipmentId()!=null){
                String token = AppJwtUtil.getToken(0l); //为所有游客根据0生成token
                Map map = new HashMap<>();
                map.put("token", token);
                return ResponseResult.okResult(map);
            }
        }
        return null;
    }
}
